import Vue from 'vue'
import VueRouter from 'vue-router'
// 登录组件
import Login from '../components/Login.vue'
// 后台主页组件
import Home from '../components/Home.vue'
// 欢迎组件
import Welcome from '../components/Welcome.vue'
// 用户列表
import Users from '../components/Users.vue'
// 角色列表
import Roles from '../components/Roles.vue'
// 权限列表
import Rights from '../components/Rights.vue'
// 商品列表
import Goods from '../components/Goods.vue'
// 分类参数
import Params from '../components/Params.vue'
// 商品分类
import Categories from '../components/Categories.vue'
// 订单列表
import Orders from '../components/Orders.vue'
// 数据报表
import Reports from '../components/Reports.vue'
// 添加商品
import Add from '../components/Add.vue'
// 编辑商品
import Edit from '../components/Edit.vue'

Vue.use(VueRouter)

const routes = [
  { path: '/', redirect: '/login' },
  { path: '/login', component: Login },
  {
    path: '/home', component: Home, redirect: '/welcome',
    children: [
      { path: '/welcome', component: Welcome },
      { path: '/users', component: Users },
      { path: '/roles', component: Roles },
      { path: '/rights', component: Rights },
      { path: '/goods', component: Goods },
      { path: '/params', component: Params },
      { path: '/categories', component: Categories },
      { path: '/orders', component: Orders },
      { path: '/reports', component: Reports },
      { path: '/goods/add', component: Add },
      { path: '/goods/edit', component: Edit },
    ]
  },
]

const router = new VueRouter({
  routes
})

// 挂载路由导航守卫
router.beforeEach((to, from, next) => {
  // to 将要访问的路径
  // from 代表从哪个路径跳转而来
  // next 是一个函数，表示放行
  //     next() 放行   next('/login') 强制跳转

  // 如果去登录页，就直接放行，其他页面都要获取token且判断token是否存在，token不存在强制跳转到登录页，存在则放行
  if (to.path === '/login') return next();
  const token = window.sessionStorage.getItem('token');
  if (!token) return next('/login');
  next();
})

export default router
